/*
Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3
Return 6.
*/

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode *root) {
        if (!root) return 0;
        int maxsum = INT_MIN;
        maxPathSumHelper(root, maxsum);
        return maxsum;
    }
private:
    int maxPathSumHelper(TreeNode *root, int &maxsum) {
        if (!root) return 0;
        int sum = root->val;
        int l = maxPathSumHelper(root->left, maxsum);
        int r = maxPathSumHelper(root->right, maxsum);
        if (l>0) sum += l;
        if (r>0) sum += r;
        if (sum > maxsum) maxsum = sum;
        if (l>0 || r>0) return max(l, r) + root->val;
        return root->val;
    }
};
